package com.sea.finance.controller;


import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.Inventory;
import com.sea.physical.entity.CreateDespatchFreight;
import com.sea.physical.service.CabinetService;
import com.sea.physical.service.CreateDespatchFreightService;
import com.sea.physical.service.CreatePlanService;
import com.sea.supply.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * 运费
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/finance/freight")
public class DespatchFreightController {

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CreateDespatchFreightService createDespatchFreightService;
    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private DictDetailService dictDetailService;

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("cabinet",cabinetService.findByCnd(null));
        model.addAttribute("country", dictDetailService.findByTypeCode("base_country", null));
        model.addAttribute("payment", dictDetailService.findByTypeCode("payment_type", null));
        return "/sea/finance/createDespatchFreight/main";
    }
    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, @RequestParam("id") Integer id) {
        model.addAttribute("freight",createDespatchFreightService.findById(id));
        return "/sea/finance/createDespatchFreight/edit";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     CreateDespatchFreight freight) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<CreateDespatchFreight> list = createDespatchFreightService.findByCnd(freight);
        PageInfo<CreateDespatchFreight> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 保存
     * @param freight
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(CreateDespatchFreight freight) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null != freight && createDespatchFreightService.save(freight) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }


    /**
     * 保存
     * @param freight
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(CreateDespatchFreight freight) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null != freight && createDespatchFreightService.usave(freight) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public AjaxReturn produce(@RequestParam("payIds")Integer[]payIds, @RequestParam("producePayTime")String producePayTime,String produceFile) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != payIds && StringUtils.isNotEmpty(producePayTime)) {
                createDespatchFreightService.pay(payIds, producePayTime,produceFile);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, CreateDespatchFreight freight) {
        List<CreateDespatchFreight> list = createDespatchFreightService.findByCnd(freight);
        String[] title = {"柜号","供应商","币种", "金额","汇率","类型", "是否付款","付款凭证","付款时间","付款方式","备注"};
        String fileName = "海运费关税表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "进销存表";
        String[][] content = new String[list.size()][11];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            CreateDespatchFreight obj = list.get(i);
            content[i][0] = obj.getCreatePlanNo();
            content[i][1] = obj.getCreateSupplier();
            content[i][2] = obj.getCreateMoneyType();
            content[i][3] = obj.getCreateMoney()+"";
            content[i][4] = obj.getCreateMoneyPercent()+"";
            Integer flag = obj.getFlag();
            if(flag==0){
                content[i][5] = "运费";
            }else if (flag==1){
                content[i][5] = "关税";
            }else if (flag==2){
                content[i][5] = "头程";
            }else if (flag==3){
                content[i][5] = "海运";
            }else if (flag==4){
                content[i][5] = "尾程";
            }else{
                content[i][5] = "";
            }

            Integer createPay = obj.getCreatePay();
            if(createPay==0){
                content[i][6] ="否";
            }else{
                content[i][6] ="是";
            }

            content[i][7] = obj.getCreatePayFile()+"";
            content[i][8] = obj.getCreatePayTime();
            content[i][9] = null==obj.getCreatePayType()?"":obj.getCreatePayType();
            content[i][10] = obj.getCreateRemark();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
